package com.dpiinc.TechPage.adapter

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import androidx.core.content.ContextCompat
import android.text.SpannableString
import android.text.Spanned
import android.text.style.ForegroundColorSpan
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.RecyclerView
import com.dpiinc.TechPage.*
import com.dpiinc.TechPage.activity.EditNoteActivity
import com.dpiinc.TechPage.api.EditNoteApi
import com.dpiinc.TechPage.repository.EditNoteRepository
import com.dpiinc.TechPage.room.RoomAiWriterDatabase
import com.dpiinc.TechPage.room.bean.NoteEntity
import com.dpiinc.TechPage.user.utils.PermissionUtils
import com.dpiinc.TechPage.user.utils.ShareHelper
import com.dpiinc.TechPage.user.utils.ToastUtils
import com.dpiinc.TechPage.user.utils.ViewToBitmapUtil
import com.dpiinc.TechPage.utils.DateUtils
import com.dpiinc.TechPage.widget.LabelsView
import com.dpiinc.TechPage.widget.swipemenu.SwipeMenuLayout
import com.beiji.lib.pen.cache.PenCacheManager
import com.bumptech.glide.RequestManager
import com.bumptech.glide.signature.ObjectKey
import java.io.File
import com.yanzhenjie.permission.Action


/**
 * 笔记item ViewHolder
 * Created by X on 2018/7/1.
 */
class NoteItemViewHolder(view: View
                         , private val glide: RequestManager
                         , private val context: Context
) : RecyclerView.ViewHolder(view) {

    private var activity: AppCompatActivity? = null
    private val topCrop = TopCrop()
    // val divider:View = view.findViewById(R.id.divider)
    private val title: TextView = view.findViewById(R.id.tv_title)
    private val time: TextView = view.findViewById(R.id.tv_time)
    //TODO 此功能暂未是实现，只添加了icon
    private var voice: ImageView = view.findViewById(R.id.iv_voice);
    private val thumbnail: ImageView = view.findViewById(R.id.iv_thumbnail)
    private val labelsView: LabelsView = view.findViewById(R.id.labels_view)
    private val content: LinearLayout = view.findViewById(R.id.content)
    private var btn_share: LinearLayout = view.findViewById(R.id.btn_share)
    private var btn_delete: LinearLayout = view.findViewById(R.id.btn_delete)
    private var btn_sure_delete: LinearLayout = view.findViewById(R.id.btn_sure_delete)
    private var note: NoteEntity? = null

    private var repository:EditNoteRepository? = null

    init {

        content.setOnClickListener {

            note?.let {
                val intent = Intent(view.context, EditNoteActivity::class.java)
                intent.putExtra(EditNoteActivity.ARG_NOTE_BEAN, it)
                view.context.startActivity(intent)
            }
        }

        btn_share.setOnClickListener {

            if (mOnSwipeListener != null) {
                (itemView as SwipeMenuLayout).quickClose()
                note?.let {
                    mOnSwipeListener!!.onClickShare(adapterPosition,it)
//                    this.handlerShareClick(it);
                }


            }
        }

        btn_sure_delete.setOnClickListener {
            if (mOnSwipeListener != null) {
                mOnSwipeListener!!.onClickDelete(adapterPosition)
                (itemView as SwipeMenuLayout).quickClose()
                note?.let {
                    handlerDeleteClick(it);
                }
            }
        }

        btn_delete.setOnClickListener {
            btn_delete.visibility = View.GONE
            btn_share.visibility = View.GONE
            btn_sure_delete.visibility = View.VISIBLE
        }
    }

    @SuppressLint("SetTextI18n")
    fun bind(appcompat: AppCompatActivity?, note: NoteEntity?, keyword: String? = null) {
        note ?: return
        appcompat ?: return
        this.note = note
        this.activity = appcompat
        repository = EditNoteRepository(RoomAiWriterDatabase.getInstance(activity?.application), EditNoteApi.create())

        val highlightString = if (AIWriteApplication.isDebug()) {
            getHighlightKeywordString("${note.noteName} -> ${note.noteId}", keyword)
        } else {
            getHighlightKeywordString(note.noteName, keyword)
        }

        btn_share.visibility = View.VISIBLE
        btn_delete.visibility = View.VISIBLE
        btn_sure_delete.visibility = View.GONE

        (itemView as SwipeMenuLayout).setOnChangeListener {
            btn_share.visibility = View.VISIBLE
            btn_delete.visibility = View.VISIBLE
            btn_sure_delete.visibility = View.GONE
        }


        title.text = highlightString
        time.text = DateUtils.getNoteDateString(if (note.modifyTime == 0L) note.createTime else note.modifyTime)
        note.label?.let {
            //最多显示3个标签
            val labels = if (it.size > 3) {
                it.subList(0, 3)
            } else {
                it
            }
            labelsView.setLabels(false, labels) { _, _, label ->
                label.content
            }
        }
        var previewImage = note.imageFiles?.preview?.fileUrl
        val dotFile = note.dotFiles?.fileUrl
        val isDotFileNotEmpty = dotFile?.isNotEmpty() ?: false
        val isPreviewNotEmpty = previewImage?.isNotEmpty() ?: false
        val previewModifyTime = note.imageFiles?.preview?.modifyTime ?: 0L
        if (isDotFileNotEmpty && isPreviewNotEmpty) {
            thumbnail.visibility = View.VISIBLE
            AWLog.i("preview", previewImage.toString())
            val localImgPath = PenCacheManager.instance.getPreview(note.noteId)
            if (File(localImgPath).exists()) {
                previewImage = localImgPath
            }

            glide.load(previewImage)
                    .transform(topCrop)
                    .signature(ObjectKey(previewModifyTime))
                    .placeholder(R.mipmap.ic_default_thumbnail)
                    .into(thumbnail)

        } else {
            thumbnail.visibility = View.INVISIBLE
        }

        var audioRecordList = note.recordFiles
        if (audioRecordList!!.isNotEmpty()) {
            voice.visibility = View.VISIBLE
        } else {
            voice.visibility = View.GONE
        }
    }

    private fun getHighlightKeywordString(text: String?, keyword: String?): SpannableString? {
        val spannableString = SpannableString(text)
        text ?: return spannableString
        keyword ?: return spannableString
        if (keyword.isNullOrEmpty()) {
            return spannableString
        }
        var startIndex = 0
        var endIndex = 0
        while (startIndex >= 0) {
            startIndex = text.indexOf(keyword, endIndex, true)
            if (startIndex < 0) {
                break
            }
            endIndex = startIndex + keyword.length
            spannableString.setSpan(ForegroundColorSpan(ContextCompat.getColor(context, R.color.theme)), startIndex, endIndex, Spanned.SPAN_INCLUSIVE_EXCLUSIVE)
        }
        return spannableString
    }

    companion object {
        fun create(
                parent: ViewGroup,
                glide: RequestManager
        ): NoteItemViewHolder {
            val view = LayoutInflater.from(parent.context)
                    .inflate(R.layout.note_list_item, parent, false)
            return NoteItemViewHolder(view, glide, parent.context)
        }
    }

    fun updateNote(item: NoteEntity?) {
        note = item
//        score.text = "${item?.score ?: 0}"
    }

    private var mOnSwipeListener: onSwipeListener? = null

    interface onSwipeListener {
        fun onClickShare(pos: Int,note: NoteEntity)

        fun onClickDelete(pos: Int)
    }

    fun setOnSwipeListener(mOnSwipeListener: onSwipeListener) {
        this.mOnSwipeListener = mOnSwipeListener
    }

    private fun handlerShareClick(it: NoteEntity) {

        val bitmapPathList: ArrayList<String> = PenCacheManager.instance.getPenStrokeBitmapPathList(it.noteId)
        setModifyTimeForShare(it)
        ViewToBitmapUtil.generateAllBitmap(context, bitmapPathList)

        checkPermissionShowDialog(bitmapPathList)

    }

    private fun setModifyTimeForShare(it: NoteEntity) {
        ViewToBitmapUtil.setShareTime(it.modifyTime);
        ViewToBitmapUtil.setShareTitle(it.noteName)
    }

    private fun checkPermissionShowDialog(bitmapPathList: ArrayList<String>) {

        val granted = Action<List<String>> {
            ShareHelper.showShareDialog(context, bitmapPathList,"")
        }
        val denied = Action<List<String>> {
            ToastUtils.showTopTip(context, AIWriteApplication.instance().resources.getString(R.string.no_authority_share))
            Log.d(EditNoteActivity.TAG, "onAction denied")
        }
       // if (PermissionUtils.checkWRITE_EXTERNAL_STORAGE(context, granted, denied)) {
            ShareHelper.showShareDialog(context, bitmapPathList,"")
    //    }

    }

    private fun handlerDeleteClick(note: NoteEntity) {
        repository?.doOperation(EditNoteRepository.OPERATION_DELETE, note)
    }

}

